import axios from "axios";
import {useTokenStore} from "@/stores/token.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {useUserStore} from "@/stores/user.js";
//创建axios对象
const service = axios.create({
    baseURL:import.meta.env.VITE_SERVER_ADDR
});
//请求拦截器
service.interceptors.request.use(req =>{
    const tokenStore = useTokenStore()
    if(tokenStore.tokenStr){
        req.headers.token=tokenStore.tokenStr;
    }
    return req;
},error => {

})
//响应拦截器
service.interceptors.response.use(resp =>{
    const token = resp.headers.token;
    if(token){
        const tokenStore = useTokenStore();
        tokenStore.updateToken(token);
    }
    return resp.data;
},error =>{
    if(error.status == 403) {
        ElMessage.error({
            message: '令牌错误，请重新登录',
            dirstance: 1200,
            onClose: () => {
                const tokenStore = useTokenStore();
                const userStore = useUserStore();
                tokenStore.$reset();
                userStore.$reset();
                //删除store中token
                let currentPath = router.currentRoute.value.path;
                if(currentPath.startsWith("/admin")){
                    router.push('/admin/login');
                }else {
                    router.push('/user/login');
                }
                //跳转到登录页面
                router.push('/login');
            }
        });
    }
})
export default service;